import request from "@/utils/request";
import React, { useCallback, useEffect, useRef, useState } from "react";
import axios from 'axios'

function getToken() {
  return request('/api/ai/token')
}

async function toMessage(evt: any, result: (text: string) => void) {

  const { data } = evt
  // 收到消息 请求api
  const res = await axios('https://open.bigmodel.cn/api/paas/v3/model-api/chatglm_std/async-invoke', {
    method: 'POST',
    headers: {
      Authorization: data.token,


    },
    data: {
      // @ts-ignore
      prompt: [{ "role": "user", "content": data.text }],
      top_p: 0.7,
      temperature: 0.9
    }
  })


  const invoke = async (id: string) => {

    const dt = await axios(`https://open.bigmodel.cn/api/paas/v3/model-api/-/async-invoke/${  id}`, {
      headers: {
        Authorization: data.token,
        ContentType: 'application/json'
      },
      method: 'GET'
    })

    if (dt.data.data.task_status === 'PROCESSING') {
      setTimeout(()=>{
        invoke(id)
      }, 3000)
    } else {
      return result(dt.data.data.choices[0].content)
    }
  }
  if (res.data.data?.task_id) {
    await invoke(res.data.data?.task_id)
  }
}

export type AITextProps = {
  isBr: boolean
}

export function useAiTextEditor(props: AITextProps = { isBr: true }) {

  const [text, setText] = useState<string>()
  const [loading, setLoading] = useState<boolean>(false)
  const tokenRef = useRef<string>()


  useEffect(() => {
    const invoke = async () => {
      if (!tokenRef.current) {
        const { data } = await getToken()
        tokenRef.current = data
      }
    }

    invoke()
  }, [])

  const sendMessage = useCallback((text: string) => {
    if (text) {
      setLoading(true)
      toMessage({
        data: {
          text,
          token: tokenRef.current
        }
      }, (dt => {
        setLoading(false)
        let tx = JSON.parse(dt)
        if (props.isBr) {
          tx = tx.replace(/\\n/g, '<br/>')
        }
        setText(tx)
      }))
    }
  }, [props])


  return {
    sendMessage,
    text,
    loading
  }

}